import { create } from "zustand";
import { immer } from "zustand/middleware/immer";
import { createJSONStorage, devtools, persist } from "zustand/middleware";
type TAppStoreType = {
  price: number;
  count: number;
  color: string;
  // increament: () => void; //void 表示没有返回值
  // decrement: () => void;
  // getTotal: () => number;
  doubleCount: () => Promise<number | any>;
};
const useAppStore = create<TAppStoreType>()(
  immer(
    persist(
      (set, get) => ({
        color: "red",
        price: 7.0,
        count: 10,
        // increament() {
        //   set((state) => {
        //     state.count++;
        //   });
        // },
        // decrement() {
        //   set((state) => {
        //     state.count--;
        //   });
        // },
        // getTotal() {
        //   return get().price * get().count;
        // },
        async doubleCount() {
          const rate = await Promise.resolve(2);
          set((state) => {
            state.count *= rate;
          });
        },
      }),
      { name: "app-Store", storage: createJSONStorage(() => sessionStorage) }
    )
  )
);
export default useAppStore;
export const getTotal = () => {
  return useAppStore.getState().price * useAppStore.getState().count;
};
export const decrement = () => {
  useAppStore.setState((state) => {
    state.count--;
  });
};
export const increament = () => {
  useAppStore.setState((state) => {
    state.count++;
  });
};
